package qe.spider.tools;

import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import qe.spider.vo.GoodStock;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class FeiShuNotice {
    private final String webHook = "https://open.feishu.cn/open-apis/bot/v2/hook/f9b98e54-d57f-4eee-8009-29fae56293e2";

    List<GoodStock> goodStocks;

    public FeiShuNotice(List<GoodStock> goodStocks) {
        this.goodStocks = goodStocks;
    }

    public static void main(String[] args) throws IOException {
        List<String> set1 = new ArrayList<>(List.of("1", "2", "3"));
        List<String> set2 = new ArrayList<>(List.of("1", "3", "5"));
        set1.retainAll(set2);
        log.debug("----" + set1);

        log.debug(NumberChineseFormatter.formatSimple(4709360063L));
        GoodStock s1 = new GoodStock();
        s1.setCode("1");
        GoodStock s2 = new GoodStock();
        s2.setCode("2");

        List<GoodStock> goodStocks = List.of(s1, s2);
        log.debug(new FeiShuNotice(goodStocks).buildJson());
    }

    public String buildJson() {
        Map<String, Object> msg = Map.of("msg_type", "interactive", "card",
                Map.of("type", "template", "data", Map.of("template_id", "ctp_AAVTrgN6hyGP", "template_variable",
                        Map.of("total_count", String.valueOf(goodStocks.size()), "group_table", goodStocks))));

        String json = new Gson().toJson(msg);
        return json;
    }

    public RequestBody formBody() {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), buildJson());
        return body;
    }

    public Boolean send() {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(webHook).header("Content-Type", "application/json").post(formBody()).build();
        log.debug(request.body().toString());
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) return false;
            String result = UnicodeUtil.toString(response.body().string());
            log.debug(result);
            return true;
        } catch (IOException e) {
            log.error("FeiShu msg send error： ", e);
        }
        return true;
    }
}
